<template>
  <div>

    <div v-if="rowArr.businessType == 'shinei'">
      <el-table class="mt20" v-loading="loading" :data="tableList" key="table1">
        <!-- <el-table-column type="selection" width="55" align="center" show-overflow-tooltip /> -->
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="autoId" align="center" prop="autoId" />
        <el-table-column label="业务类型" align="center" prop="category">
          <template slot-scope="scope">
            {{detection_type[scope.row.category]}}
          </template>
        </el-table-column>
        <el-table-column label="试验项目" align="center" prop="project">

          <template slot-scope="scope">
            <div>
              <div>{{ detectionOptions[scope.row.project] }}
                <!-- <span style="color: #1890ff;">{{ scope.row.number }}</span> -->
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="数量" align="center" prop="number" />
        <el-table-column label="单位" align="center" prop="unit" />
        <!-- <el-table-column label="标准工日" align="center" prop="workHours" /> -->
        <el-table-column label="试验员" align="center" prop="chargePerson">
          <template slot-scope="scope">
            <span>{{ scope.row.nickName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="isDone" >
          <template slot-scope="scope">
            <span v-if="scope.row.isDone == 1">进行中</span>
            <span v-else>完成</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->

        <!-- <el-table-column label="预估水平/抗拔极限值(K/N)" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type" />
        </template>
      </el-table-column>-->
      <!-- <el-table-column label="状态" align="center" prop="isDone" >
          <template slot-scope="scope">
            <span v-if="scope.row.isDone == 1">进行中</span>
            <span v-else>完成</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="100%" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>




    <div v-if="rowArr.businessType == 'shiwai'">
      <el-table class="mt20" :data="shiwaitableList" key="table2">
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="autoId" align="center" prop="autoId" />
        <el-table-column label="类型" align="center" prop="category" >
          <template slot-scope="scope">
            {{detection_type[scope.row.category]}}
          </template>
        </el-table-column>
        <!-- <el-table-column label="桩号" align="center" prop="pileNumber" />
        <el-table-column label="桩型" align="center" prop="pileType" /> -->
        <el-table-column label="工程名称" align="center" prop="engineeringName" width="120" />
        <el-table-column label="试验人" align="center" prop="nickName" />
        <el-table-column label="数量" align="center" prop="amount" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="试验方法" align="center" prop="testMethod" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="状态" align="center" prop="isDone" >
          <template slot-scope="scope">
            <span v-if="scope.row.isDone == 1">进行中</span>
            <span v-else>完成</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100%" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleshiwaiUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="handleshiwaiDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total1 > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getshiwai" />

    </div>
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="openSampleDialog" width="500px"
      append-to-body>
      
        <div v-if="rowArr.businessType == 'shinei'">
          <el-form :inline="true" v-model="formParams" ref="shineiform" :model="formParams" label-width="110px" :rules="rules2"  >
            
            <el-row>
              <el-col :span="24">
                <el-form-item label="试验项目" prop="project"  >
                  <el-select v-model="formParams.project" placeholder="请选择" @change="handleSampleChange($event)"  >
                    <el-option v-for="item in projectOptions" :key="item.dictValue" :label="item.dictLabel"
                      :value="item.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="数量" prop="number" >
                  <el-input type="input" v-model="formParams.number"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="单位" prop="unit" >
                  <el-input type="input" v-model="formParams.unit"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="试验人员" prop="nickName" >
                  <el-select v-model="formParams.nickName" value-key="userId" placeholder="请选择" @change="onchargperson">
                    <el-option v-for="item in experimenter1" :value="item.userId" :key="item.userId"
                      :label="item.nickName"></el-option>
                  </el-select>
                  <!-- <el-input type="input" v-model="formParams.chargePerson"></el-input> -->
                </el-form-item>
              </el-col>
              <!-- <el-col :span="24">
                <el-form-item label="备注">
                  <el-input type="input" v-model="formParams.remark"></el-input>
                </el-form-item>
              </el-col> -->
            </el-row>
          </el-form>
        </div>
        
        <div v-if="rowArr.businessType == 'shiwai'">
          <el-form :inline="true" v-model="formParams" ref="shiwaiform" :model="formParams" label-width="110px" :rules="rules"  >
            <el-row class="margin-bottom-10">
              <el-col :span="24">
                <el-form-item label="试验项目" prop="testMethod">
                  <el-select v-model="formParams.testMethod" placeholder="请选择" @change="handleAttachedDataChange($event)" >
                      <el-option v-for="item in projectOptions1" :key="item.dictValue" :label="item.dictLabel"
                      :value="item.dictLabel"></el-option>
                  
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row class="margin-bottom-10">
              <el-col :span="24">
                <el-form-item label="数量"  prop="amount">
                  <el-input type="input" v-model="formParams.amount"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="单位" prop="unit" >
                  <el-input type="input" v-model="formParams.unit"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row class="margin-bottom-10">
              <el-col :span="24">
                <el-form-item label="试验人" prop="nickName">
                  <el-select v-model="formParams.nickName" value-key="userId" placeholder="请选择"
                    @change="onchargperson" >
                    <el-option v-for="item in experimenter" :value="item.userId" :key="item.userId"
                      :label="item.nickName"></el-option>
                  </el-select>
                  <!-- <el-input type="input" v-model="formParams.chargePerson"></el-input> -->
                </el-form-item>
              </el-col>
            </el-row>
          
          </el-form>
        </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
    <el-row class="mt20">
      <el-col style="text-align: center;margin-top:15px" :span="24">
        <el-button type="primary" @click="onAdd">新增</el-button>
        <el-button @click="onclose">关闭</el-button>

        <!-- <el-button type="primary" @click="updateDone">检测完结</el-button> -->
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getSampleList, addSampleList, getSampleListdt, delSampleList, updateSampleList, getAttachedData, addAttachedData, DelAttachedDatalist, getAttachedDatadetail, updateAttachedData
} from "@/api/enterprise/enterprise";
import {
  listUser, listAllUser
} from "@/api/system/user.js";

import {
  updateDone
} from "@/api/commission/commission.js";
import { Notification, MessageBox, Message } from 'element-ui'

export default {
  data() {
    return {
      detectionOptions: [],
      shiwaiId: '',
      total: 0,
      total1: 0,
      ismoban1: false,
      ismoban2: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      loading: false,
      isShiWai: false,
      isShinei: false,
      title: '',
      rowArr: {},
      tableList: [],
      shiwaitableList: [],
      projectOptions: [],
      projectOptions1:[],
      openSampleDialog: false,
      form: {},
      shiwaiform:{},
      shineiform:{},
      formParams: {
        chargePerson: ''

      },
      statusOptions: [],
      experimenter: [],
      experimenter1:[],

      detection_type:[],

      rules: {
        testMethod: [
          { required: true, message: "试验项目不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "实验人员不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
      },

      rules2: {
        project: [
          { required: true, message: "试验项目不能为空", trigger: "blur" }
        ],
        number: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "实验人员不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
      },

    };
  },
  mounted() {
    if (this.rowArr.businessType == 'shinei') {
      this.getList()
    }
    if (this.rowArr.businessType == 'shiwai') {
      this.getshiwai()
    }
  },
  created() {
     this.getCombinedUsers(); 
    this.getjclb()
    this.getUser()
    // this.getList()
    // this.getshiwai()
    this.rowArr = JSON.parse(this.$route.query.row)
    console.log(this.rowArr,'111')
    
    
    this.getDicts("detection_type").then(response => {
      // this.mangementOptions = response.data;
      let data = response.data
      let new_arr = [];
      data.forEach(function (item) {
        new_arr[item.dictValue] = item.dictLabel
      });
      this.detection_type = new_arr;
    });

    //室外字典
    this.getDicts("detection_item_scene").then(response => {
         this.projectOptions1 = response.data
    })
    //室内字典
    this.getDicts("detection_item_indoor").then(response => {
      console.log(response)
      this.projectOptions = response.data
      let data = response.data
      let new_arr = [];
      data.forEach(function (item) {
        new_arr[item.dictValue] = item.dictLabel
      });
      this.detectionOptions = new_arr;
    });

  },
  methods: {
    cancel() {
      this.openSampleDialog = false
    },
    getjclb() {
      this.getDicts("detection_type").then(response => {
        this.statusOptions = response.data;
      });
    },
    onChangeMoban(val) {
      console.log(val)
      if (val == 1) {
        this.ismoban1 = true
        this.ismoban2 = false
      } else {
        this.ismoban2 = true
        this.ismoban1 = false
      }
    },
    onchargperson(val) {
      let selectedItem = this.experimenter.find(item => item.userId === val); 
      this.formParams.chargePerson = val
      this.formParams.nickName = selectedItem.nickName
    },
    // 合并两个请求并合并负责人和劳务人员
  async getCombinedUsers() {
    try {
      // 并行请求两个接口
      const [role5Users, role7Users] = await Promise.all([
        listAllUser({ roleId: 5 }),
        listAllUser({ roleId: 7 })
      ]);
      
      // 合并结果并去重
      const combinedUsers = [...role5Users.data, ...role7Users.data];
      const uniqueUsers = combinedUsers.filter(
        (user, index, self) => index === self.findIndex(u => u.userId === user.userId)
      );
      
      this.experimenter = uniqueUsers;
    } catch (error) {
      console.error('获取用户失败:', error);
    }},


    getUser() {
      listAllUser({ roleId: 5 }).then(res => {
        this.experimenter1 = res.data
      })
    },
  
    onclose() {
      this.$router.go(-1)
      // this.openSampleDialog = false
    },
    onAdd() {
      this.title = '新增试验项目'
      this.openSampleDialog = true
      this.reset()
    },
    getList() {
      let obj = {
        commissionId: this.rowArr.id,
        engineeringId: this.rowArr.engineeringId,
        pageNum: 1,
        pageSize: 10,
      }
      getSampleList(obj).then(response => {
        this.tableList = response.rows;
        this.total = response.total;
        // this.isShinei = true
        this.loading = false;
      });
    },
    getshiwai() {
      let obj = {
        pageNum: 1,
        pageSize: 10,
        commissionId: this.rowArr.id
      }
      getAttachedData(obj).then(res => {
        this.shiwaitableList = res.data;
        this.total1 = res.total;
        // this.isShiWai = true
        // this.loading = false;
      })
    },
    submitForm() {
      this.formParams.type = this.rowArr.type
      this.formParams.category = this.rowArr.businessType
      let rowid = this.rowArr
      if (rowid.businessType == 'shiwai') {
        console.log("gdsgsd")
        this.$refs["shiwaiform"].validate(valid => {
          if(valid){
            if (this.formParams.id != null) {
              updateAttachedData({ ...this.formParams, id: this.shiwaiId, engineeringId: this.rowArr.engineeringId }).then(res => {
                this.msgSuccess("修改成功");
                this.getshiwai()
                this.openSampleDialog = false
              })
            }else{
              addAttachedData({ ...this.formParams, status: 2, commissionId: this.rowArr.id, engineeringId: this.rowArr.engineeringId }).then(res => {
                this.msgSuccess("添加成功");
                this.getshiwai()
                this.openSampleDialog = false
                this.reset()
              })
            }
          }
        })
      }

      if (rowid.businessType == 'shinei') {
        this.$refs["shineiform"].validate(valid => {
          if(valid){
            if (this.formParams.id != null) {
              updateSampleList(this.formParams).then(res => {
                this.msgSuccess("修改成功");
                this.getList()
                this.openSampleDialog = false
              })
            }else{
              addSampleList({ ...this.formParams, status: 2, commissionId: rowid.id, engineeringId: rowid.engineeringId }).then(res => {
                this.msgSuccess("添加成功");
                this.getList()
                this.openSampleDialog = false
                this.reset()
              })
            }
          }
        })
      }

  /*
      this.$refs["form"].validate(valid => {
        if(valid){
          this.formParams.type = this.rowArr.type
          this.formParams.category = this.rowArr.businessType
          // this.formParams.chargePerson = this.formParams.nickName
          let rowid = this.rowArr
          if (this.formParams.id != null) {
            if (rowid.businessType == 'shinei') {
              
              updateSampleList(this.formParams).then(res => {
                this.msgSuccess("修改成功");
                this.getList()
                this.openSampleDialog = false
              })
            } else if (rowid.businessType == 'shiwai') {

              updateAttachedData({ ...this.formParams, id: this.shiwaiId, engineeringId: rowid.engineeringId }).then(res => {
                this.msgSuccess("修改成功");
                this.getshiwai()
                this.openSampleDialog = false
              })
            }

          } else {
            if (rowid.businessType == 'shinei') {
              addSampleList({ ...this.formParams, status: 2, commissionId: rowid.id, engineeringId: rowid.engineeringId }).then(res => {
                this.msgSuccess("添加成功");
                this.getList()
                this.openSampleDialog = false
                this.reset()

              })
            } else if (rowid.businessType == 'shiwai') {
              addAttachedData({ ...this.formParams, status: 2, commissionId: rowid.id, engineeringId: rowid.engineeringId }).then(res => {
                this.msgSuccess("添加成功");
                this.getshiwai()
                this.openSampleDialog = false
                this.reset()
              })

            }
          }
        }

      })
*/

    },
    reset1() {
      this.form = {

      }
      this.resetForm("form");
    },
    reset() {
      this.formParams = {
        category: "",
        number: '',
        workHours: '',
        chargePerson: '',
        amount: '',
        remark: "",
        type: '',
        pileNumber: '',
        pileType: '',
        pileLength: '',
        diameter: '',
        pileLayer: '',
        goneStrength: '',
        compressionOne: '',
        pileDate: '',
        testMethod: '',
        testNumber: '',
        position: '',
        bearingStratum: '',
        bearingValue: '',
        constructionTime: '',
        status: '',
      }
      this.resetForm("formParams");
    },
    handleshiwaiDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function () {
          return DelAttachedDatalist(ids);
        })
        .then(() => {
          this.getshiwai();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function () {
          return delSampleList(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //this.reset();
      const id = row.id || this.ids;
      getSampleListdt(id).then(response => {
        this.formParams = response.data;
        this.openSampleDialog = true;
        this.title = "修改试验项目";
      });
    },
    handleshiwaiUpdate(row) {
      this.shiwaiId = row.id
      const id = row.id || this.shiwaiId;
      getAttachedDatadetail(id).then(response => {
        this.formParams = response.data;
        if (this.formParams.type == 1) {
          this.ismoban1 = true
          this.ismoban2 = false
        } else {
          this.ismoban1 = false
          this.ismoban2 = true
        }
      
        // this.$nextTick(() => {
        //   const obj = this.experimenter.find((item) => {
        //     return item.userId === Number(response.data.chargePerson);
        //   });
        //     //  console.log(this.experimenter, Number(response.data.chargePerson),'000');//获取的item所有的值
        //   this.formParams.chargePerson = obj ? obj.nickName : '';
        //   })
        this.openSampleDialog = true;
        this.title = "修改试验项目";
      });
    },

    //试验完结 按钮
    updateDone(){
      console.log("done")
      let commissionId = this.rowArr.id
      updateDone(commissionId).then(response => {
        if(response.code == 200){
          Message({
            message: response.msg,
            type: 'success',
            duration: 5 * 1000
          })
        }
      });
    },

    handleAttachedDataChange(val){
      let experimentItemOptions = this.projectOptions1
      let unit = "";
      experimentItemOptions.forEach(function (item) {
         if(val == item.dictLabel){
          unit = item.cssClass
         } 
      })
      this.formParams.unit = unit;
    },
    handleSampleChange(val){
      console.log(val)
      let experimentItemOptions = this.projectOptions
      console.log(experimentItemOptions)
      let unit = "";
      experimentItemOptions.forEach(function (item) {
         if(val == item.dictValue){
          unit = item.cssClass
         } 
      })
      this.formParams.unit = "组";

    },

  }
};
</script>

<style scoped>
/* .el-input{
    width: 200px;
} */
v-deep .el-form-item .el-form-item__content {
  margin-left: 0;
}
</style>